package com.teach.api;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.teach.Const;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;

@Controller
@RequestMapping("/api")
public class KaptchaAPI {
	
	private final static Logger log = LoggerFactory.getLogger(KaptchaAPI.class);

	@GetMapping("kaptcha")
	public String doKaptcha(HttpServletResponse response,HttpSession session,
			@RequestParam(defaultValue = "200") Integer width,
			@RequestParam(defaultValue = "90") Integer height,
			@RequestParam(defaultValue = "4") Integer codeCount,
			@RequestParam(defaultValue = "4") Integer thickness
			) throws Throwable {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(width, height, codeCount, thickness);
        String code = captcha.getCode();
        session.setAttribute(Const.KAPTCHA_SESSION_NAME, code);
        log.debug("验证码：{}",code);
        captcha.write(out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
	}
}
